//
//  UITextViewEditViewController.swift
//  FutureBull
//
//  Created by IronMan on 2021/3/17.
//  Copyright © 2021 wuyanwei. All rights reserved.
//
// MARK:- UITextView 编辑的类
import UIKit

enum FBTextViewEditType {
    /// 简介
    case introduction
}

class UITextViewEditViewController: UIViewController {
    /// 编辑后的闭包
    var editTextClosure: EditTextClosure?
    /// 编辑的类型
    private var editType: FBTextViewEditType?
    /// 头部标题
    private var titleName: String = ""
    /// 默认内容
    private var content: String?
    /// 占位符
    private var placeholder: String = ""
    /// 输入的最多字符
    private var maxCharacters: Int = 0
    /// 底部提示文字
    private var bottomTipString: String?
    /// 内容的输入规则
    private var regex: String?
    
    lazy var textView: UITextView = {
        let filed = UITextView(frame: CGRect(x: 17, y: 17, width: kScreenW - 15 - 15, height: 117 - 17 - 37))
        filed.font = UIFont.systemFont(ofSize: 16)
        // 内容缩进为0（去除左右边距）
        filed.textContainer.lineFragmentPadding = 0
        // 文本边距设为0（去除上下边距）
        filed.textContainerInset = .zero
        if let weakContent = content {
            filed.text = weakContent
        }
        filed.textAlignment = .left
        filed.textColor = .c444444
        filed.delegate = self
        filed.placeholder = placeholder
        filed.placeholdFont = UIFont.systemFont(ofSize: 16)
        filed.placeholdColor = .gray
        filed.placeholderOrigin = CGPoint(x: 2, y: 4)
        return filed
    }()
    
    /// 总数字
    lazy var allNumberLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 14)
        label.textAlignment = .right
        label.textColor = .black
        label.text = "/\(maxCharacters)"
        return label
    }()
    
    /// 输入的数字
    lazy var inputNumberLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 14)
        label.textAlignment = .right
        label.textColor = .c444444
        if let weakContent = content {
            label.text = "\(weakContent.count)"
        }
        return label
    }()
    
    /// 底部提示的文字
    lazy var bottomTipLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 14)
        label.textAlignment = .left
        label.textColor = .gray
        if let weakBottomTipString = bottomTipString {
            label.text = weakBottomTipString
        }
        return label
    }()
    
    /// 背景图
    lazy var backView: UIView = {
        let bgView = UIView()
        bgView.backgroundColor = .white
        return bgView
    }()
    
    /// 完成的颜色
    lazy var doneButtonItem: UIBarButtonItem = {
        let buttonItem = UIBarButtonItem(title: "完成", style: .plain, target: self, action: #selector(doneClick))
        buttonItem.tintColor = .blue
        buttonItem.isEnabled = false
        return buttonItem
    }()
    
    init(editType: FBTextViewEditType, titleName: String, placeholder: String, maxCharacters: Int, content: String?, regex: String? = nil, bottomTipString: String) {
        super.init(nibName: nil, bundle: nil)
        self.editType = editType
        self.titleName = titleName
        self.placeholder = placeholder
        self.maxCharacters = maxCharacters
        self.regex = regex
        if let weakContent = content {
            self.content = weakContent.count > maxCharacters ? weakContent.jk.sub(to: maxCharacters) : weakContent
        } else {
            self.content = content
        }
        self.bottomTipString = bottomTipString
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navUI()
        initUI()
        commonUI()
        updateTheme()
    }
    
    /// 导航栏的设置
    private func navUI() {

        self.view.backgroundColor = UIColor.white
        
        let navTitleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 44))
        navTitleLabel.font = UIFont.systemFont(ofSize: 19)
        navTitleLabel.textAlignment = .center
        navTitleLabel.textColor = UIColor.c444444
        navTitleLabel.text = titleName
        self.navigationItem.titleView = navTitleLabel
        
        self.navigationItem.rightBarButtonItem = doneButtonItem
    }
    
    /// 创建控件
    private func initUI() {
        self.view.addSubview(backView)
        backView.addSubview(textView)
        backView.addSubview(allNumberLabel)
        backView.addSubview(inputNumberLabel)
        
        if bottomTipString != nil {
            self.view.addSubview(bottomTipLabel)
        }
    
        textView.becomeFirstResponder()
    }
    
    /// 添加控件和设置约束
    private func commonUI() {
        backView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.top.equalTo(kNavFrameH + 10)
            make.right.equalToSuperview()
            make.height.equalTo(117)
        }
        
        allNumberLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(-12)
            make.height.equalTo(16)
            make.right.equalTo(-15)
            make.width.lessThanOrEqualTo(100)
        }
        
        inputNumberLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(-12)
            make.height.equalTo(16)
            make.right.equalTo(allNumberLabel.snp_left)
            make.width.lessThanOrEqualTo(100)
        }
        
        if bottomTipString != nil {
            bottomTipLabel.snp.makeConstraints { (make) in
                make.left.equalTo(14)
                make.top.equalTo(backView.snp_bottom).offset(15)
                make.right.equalTo(-14)
                make.height.greaterThanOrEqualTo(16)
            }
        }
    }
    
    /// 更新控件的颜色，字体，背景色等等
    private func updateTheme() {
        
    }
    
    @objc func doneClick() {
        
        guard let text = textView.text, text.count > 0 else {
            // "请输入内容".fb_toast()
            return
        }
        // 简介
        if editType == .introduction {
            updateIntroduction()
            return
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        textView.resignFirstResponder()
    }
}

// MARK:- 完成接口的调用
extension UITextViewEditViewController {
    // MARK: 更新用户的简介
    func updateIntroduction() {
        
       
    }
}

extension UITextViewEditViewController: UITextViewDelegate {
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        let result = text.jk.isNineKeyBoard()
        print("结果是：\(result) 内容：\(text)")
        return textView.jk.inputRestrictions(shouldChangeTextIn: range, replacementText: text, maxCharacters: maxCharacters, regex: regex)
    }
 
    func textViewDidChange(_ textView: UITextView) {
        inputNumberLabel.text = "\(textView.text.count > maxCharacters ? maxCharacters : textView.text.count)"
        
        let text = textView.text
        // 没有修改内容颜色不可修改
        doneButtonItem.tintColor = text == content ? UIColor.gray : UIColor.blue
        doneButtonItem.isEnabled = text == content ? false : true
    }
}
